package com.hdd.biz.task;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdd.utils.http.HttpClient;
import com.hdd.utils.http.OkHttpResponse;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 
 * @ClassName: WechatFlushAccessTokenJob
 * @Description: 每两小时刷新微信接口调用凭证，公众号
 * @author yangjian
 *
 */
@Component
@Configurable
@EnableScheduling
public class WechatFlushAccessTokenJob {
    
    @Value("${wx.gzhAppid}")
    private String appID;// 小程序id
    @Value("${wx.gzhAppsecret}")
    private String appsecret;

    private static String access_token;//微信接口调用凭证
    private static Long expires_in = 0L;
    
    public WechatFlushAccessTokenJob() {
        refreshAccessToken();
    }
    //每两小时执行一次
    @Scheduled(cron = "0 0 0/2  * * * ")
    public void execute(){
        refreshAccessToken();
    }
    
    public String getAccessToken(){
        if (access_token == null || "".equals(access_token) || System.currentTimeMillis() > expires_in) {
            refreshAccessToken();
        }
        return access_token;
    }

    public String getNewAccessToken(){
        refreshAccessToken();
        return access_token;
    }

    private void refreshAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
        OkHttpResponse<String> jsonData = HttpClient.doGet(url + "&appid=" + appID + "&secret=" + appsecret);
        JSONObject jsonObject = JSON.parseObject(jsonData.getData());
        access_token = jsonObject.getString("access_token");
        if (jsonObject.containsKey("expires_in")) {
            long expiresIn = Long.parseLong(jsonObject.getString("expires_in"));
            expires_in = System.currentTimeMillis() + expiresIn * 1000;
        }
    }

}
